package task12;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import org.omg.CORBA.IRObject;


/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/27 9:07
 * @description:统计键盘输入的各单词个数
 */
public class Task12 {

  public static void main(String[] args ) {
    /* 1、接收用户输入一句英语，单词间以空格分隔*/
    System.out.println("请输入一句英语，单词间以空格分隔");
    Scanner scanner = new Scanner(System.in);
    String sentence = scanner.nextLine();

    /*  2、将这一串字符串以空格分隔出单词,保存在数组中*/
    String[] words = sentence.split(" ");
    HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
    /*  3、利用HashMap保存：单词做key，次数做value
     *     循环单词数组：
     *        若hashMap中不存在该单词，则加到该集合对象，且value为1
     *        若存在该单词，则取出该key对应的值并+1*/
    for (int i = 0; i < words.length; i++) {
      String key = words[i];
      if (hashMap.containsKey(key)) {
        Integer value = hashMap.get(key);
        value = value + 1;
        hashMap.put(key, value);
      } else {
        hashMap.put(key, 1);
      }
    }

    /*  4、遍历HashMap，就得出每个单词出现的次数*/
    Iterator iterator=hashMap.entrySet().iterator();
    while (iterator.hasNext()){
      Map.Entry<String,Integer> entry= (Entry<String, Integer>) iterator.next();
      String key=entry.getKey();
      Integer value=entry.getValue();
      System.out.println(key+": "+value);
    }


  }

}
